<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="../../../Themes/default/easyui.css">
		<link rel="stylesheet" type="text/css" href="../../../Themes/icon.css">
		<link rel="stylesheet" type="text/css" href="../../../CSS/demo.css">
		<link rel="stylesheet" type="text/css" href="../../../CSS/common.css">
	</head>

	<body style="padding:0px;background-color: white">
		<div id="toolbar" class="receipts_toolbar_style"></div>
		<div style="float: right;margin-top: 0px;max-width:60px;" id="notreview"></div>
		<form id="ff" action="#" method="post">
			<table cellpadding="5" class="displaytable" style="text-align: left;width: 80%;margin: 0 auto;">
				<tr>
					<td width="20%">
						<h id="star">* </h>采购员</td>
					<td width="30%">
						<input class="easyui-textbox" style="width: 100%" type="text" id="input_PURCHASE_MAN" name="PURCHASE_MAN" />
					</td>
					<td width="20%">
						<h id="star">* </h>用户组</td>
					<td width="30%">
						<input class="easyui-textbox" style="width: 100%;" type="text" name="CUSTOMER_TYPE" id="input_CUSTOMER_TYPE" data-options="disabled:true"></input>
					</td>
				</tr>
				<tr>
					<td>
						<h id="star">* </h>采购时间</td>
					<td>
						<input class="easyui-datebox" style="width: 100%;" type="text" name="PURCHASE_DATE" id="input_PURCHASE_DATE" data-options="required:'true'"></input>
					</td>
					<td>
						<h id="star">* </h>采购单号</td>
					<td>
						<input class="easyui-textbox" style="width: 100%;" type="text" name="ORDER_NO" id="input_ORDER_NO" data-options="disabled:true"></input>
					</td>
				</tr>
				<tr>
					<td>
						<h id="star">* </h>仓库</td>
					<td>
						<input class="easyui-combobox" style="width: 100%;" type="text" name="STOREHOUSE_NAME" id="input_STOREHOUSE_NAME"></input>
					</td>
					<td>
						<h id="star">* </h>合计数量</td>
					<td>
						<input class="easyui-textbox" style="width: 100%;" type="text" name="PURCHASE_AMOUNT" id="input_PURCHASE_AMOUNT" data-options="disabled:true"></input>
					</td>

				</tr>
				<tr id="nodisplay" style="display: none">
					<td>
						<h id="star">* </h>仓库ID</td>
					<td>
						<input class="easyui-textbox" style="width:100%;" type="text" name="STOREHOUSE_ID" id="input_STOREHOUSE_ID" data-options="prompt:'由系统自动生成，不需填写',disabled:true," />
					</td>
					<td>
						<h id="star">* </h>采购单ID</td>
					<td>
						<input class="easyui-textbox" style="width: 100%;" type="text" name="ID" id="input_ID" data-options="disabled:true"></input>
					</td>

				</tr>
			</table>
			<table id="tt">

			</table>
			<div style="margin-left: 20%;" id="new_footer">
			</div>

		</form>

		</div>

		<div id="dlg" class="hiddenDialog">
			<iframe id="ifrmEdit" style="width: 100%;height: 100%;" frameborder="0" scrolling="no"></iframe>
		</div>

	</body>
	<script type="text/javascript" src="../../../JS/jquery.min.js"></script>
	<script type="text/javascript" src="../../../JS/jquery.easyui.min.js"></script>
	<script type="text/javascript" src="../../../JS/common.js"></script>
	<script type="text/javascript" src="../../../JS/finance.js"></script>
	<script type="text/javascript" src="../../../JS/jquery.edatagrid.js"></script>
	<script type="text/javascript" src="../../../JS/detailView.js" ></script>
	<script type="text/javascript" src="../../../JS/SHA-1.js"></script>
	<script type="text/javascript">
		var currid = AddFlag; //当前页面的ID
		var id = getID(); //获取上个页面传回的ID
		var currPage = 0; //当前的页数
		var MaxPage = 0;
		var MinPage = 1;
		var _dataPage;
		var updateData;
		var updateLog = "";
		var _detailToolbarData;
		var isVerify = 0;
		_detailToolbarData = AddDetailToolBar(2);
		GetDetailTable();
		$(document).ready(function(){
			if(id != AddFlag && id != undefined) {
			currid = id;
			loadRemote();
		}
		});

		if(id == undefined) { //如果没有数据
			currid = AddFlag;
		}
		var AddDialog;
		///增加脚注
		getPageMaxAndMin();
		addFooter($("#new_footer"));
		//增加单据的toolbar
		var receipts_type = RECEIPT_FRONT_SYMBOL;
		receipts_type += RECEIPT_NEXT_SYMBOL;
		receipts_type += RECEIPT_ADD_SYMBOL;
		receipts_type += RECEIPT_SAVE_SYMBOL;
		receipts_type += RECEIPT_DELETE_SYMBOL;
		receipts_type += RECEIPT_VERIFY_SYMBOL;
		receipts_type += RECEIPT_UNVERIFY_SYMBOL;
		receipts_type += RECEIPT_SEARCH_SYMBOL;
		receipts_type += RECEIPT_PRINT_SYMBOL;
		receipts_type += RECEIPT_EXPORT_SYMBOL;
		///tooldata为新增的toolbar数据
		content = AddReceiptsToolBar(receipts_type, "");
		$("#toolbar").append(content); /*在ID=toolbar的标记后面添加content中的内容*/

		///配送单位的模糊查询
		$('#input_customer_name').combobox({
			valueField: 'CUSTOMER_NAME',
			textField: 'CUSTOMER_NAME',
			panelWidth: 200,
			panelHeight: 'auto',
			mode: 'remote',
			method: 'get',
			onChange: function(newValue, oldValue) {
				if(newValue != "" && newValue != undefined) {
					var url = RemoteLinkAddress + "/logistics/customer/findbypinyin?PINYINFIELDNAME=" + newValue.trim();
					$(this).combobox("reload", url);
				}
			},
			onSelect: function(record) { //当选中数据后调用该function，并得到该combobox对应的valuefield和textfield，赋值给record
				$('#input_customer_id').textbox('setValue', record.ID);
				$('#input_CUSTOMERTYPE_ID').textbox('setValue', record.TYPE_ID);
				$('#input_CUSTOMER_TYPE').textbox('setValue', record.CUSTOMER_TYPE);
			} //调用easyui的textbox的写入值方法，将record中name为CUSTOMER_ID的写入id为customer_id的textbox中
		});

		function getPageMaxAndMin() {
			var _url = RemoteLinkAddress + "/logistics/purchaseorder/getmaxminid.do";
			$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
				type: "get",
				url: _url,
				dataType: "json", //服务器返回的数据类型
				success: function(result) {
					if(result != null) {
						MaxPage = result.MAXID;
						MinPage = result.MINID;
						currPage = result.MINID + 1;
					}
				}, //请求成功后，接受服务器传来的Json字符串，并做相应的处理
				error: function(xhr, status, error) {
					$.messager.alert("错误", "请求失败!");
				}
			});
		}
		///单据相关功能

		function newdata() {
			AddTabIn("创建采购单明细", parent.$('#tabs'), "UI/LOGISTICS/PurchaseOrderCreate/PurchaseOrderDetailCreate.html");
		}

		function save() {
			if(isVerify == 1) {
				$.messager.alert("警告", "审核后不允许修改");
				return;
			}
			getUpdateData();
		}

		function deletedata() {
			console.log($("#tt").datagrid('getRows'));
			if(isVerify == 0) {
				$.messager.confirm('Confirm', '是否删除', function(r) {
					if(r) {
						$.post(RemoteLinkAddress + "/logistics/purchaseorder/delete.do", {
								"ID": currid
							},
							function(result) {
								if(result.msg == "success") {
									$('#tt').datagrid('reload'); // reload the user data
									$.messager.alert({ // show success message
										title: '成功',
										msg: '删除成功'
									});
									nextpage();
								} else {
									$.messager.alert({ // show error message
										title: 'Error',
										msg: result.msg
									});
								}
							},
							'json');
					}
				});
			} else {
				$.messager.alert("提示", "该单据已审核，不能删除！");
			}

		}

		function print() {
			if(isVerify == 0) {
				$.messager.alert("警告", "订单未审核不能打印");
				return;
			}
			var pLocation = "";
			if(currid == AddFlag) {
				$.messager.alert("错误", "当前页面为新增页面不能打印");
				return;
			} else {
				pLocation = "PurchaseOrderPrint.html?id=" + currid;
				window.open(pLocation);
			}
		}

		function frontpage() {
			if(currPage > MinPage) {
				var _url = RemoteLinkAddress + '/logistics/purchaseorder/pre.do?ID=' + currid;
				getRemoteData(_url);
			} else {
				$.messager.alert("提示", "没有上张");
			}
		}

		function nextpage() {
			console.log(currPage);
			if(currPage < MaxPage) {
				var _url = RemoteLinkAddress + '/logistics/purchaseorder/next.do?ID=' + currid;
				getRemoteData(_url);
			} else {
				$.messager.alert(" 提示", "没有下张");
			}
		}

		function verifydata() {
			if(currid == AddFlag) {
				$.messager.alert('提示信息', '该页面为新增页面，不能审核！');
				return;
			}
			var a = checkDataIntegrity();
			if(a != 0) {
				if(_dataPage.ISVERIFY == 1) {
					$.messager.alert("提示", "该订单已通过审核！无需再审核！");
					return;
				}
				$.messager.confirm('Confirm', '是否审核', function(r) {
					if(r) {
						$.post(RemoteLinkAddress + "/logistics/purchaseorder/verify.do", {
								"ID": currid,
							},
							function(result) {
								if(result.msg == "success") {
									$.messager.alert({ // show error message
										title: '成功',
										msg: '审核成功!'
									});
									_dataPage.ISVERIFY = "1";
									isVerify = "1";
									verifyStatus(_dataPage.ISVERIFY, true);
								} else {
									$.messager.alert({ // show error message
										title: 'Error',
										msg: result.msg
									});
								}
							},
							'json');
					}
				});
			} else {
				$.messager.alert("失败", "请将页面中的数据补充完整后再进行审核！");
			}
		}

		function unverifydata() {
			if(currid == AddFlag) {
				$.messager.alert('提示信息', '该页面为新增页面，不能弃审！');
				return;
			}
			if(_dataPage.ISVERIFY == 0) {
				$.messager.alert("提示", "该订单已弃审！无需再弃审！");
				return;
			}
			if(_dataPage.STATE == "入库中") {
				$.messager.alert("提示", "该订单正在入库中！不能弃审！");
				return;
			}
			if(_dataPage.STATE == "入库完成") {
				$.messager.alert("提示", "该订单已全部入库！不能弃审！");
				return;
			}
			$.messager.confirm('Confirm', '是否弃审', function(r) {
				if(r) {
					$.post(RemoteLinkAddress + "/logistics/purchaseorder/unverify.do", {
							"ID": currid,
						},
						function(result) {
							if(result.msg == "success") {
								$.messager.alert({ // show error message
									title: '成功',
									msg: '放弃审核成功!'
								});
								_dataPage.ISVERIFY = "0";
								isVerify = 0;
								verifyStatus(_dataPage.ISVERIFY, true);
							} else {
								$.messager.alert({ // show error message
									title: 'Error',
									msg: result.msg
								});
							}
						},
						'json');
				}
			});
		}

		function searchmore() {
			AddTabIn("采购单查询", parent.$('#tabs'), "UI/LOGISTICS/PurchaseOrder/PurchaseOrderSearch.html");
		}

		function loadRemote() { //载入服务器上的数据，用于修改以及查看更多的时候调用，根据id是否等于-1来判断
			var _url = RemoteLinkAddress + '/logistics/purchaseorder/findbyid.do?ID=' + currid;
			getRemoteData(_url);
		}

		function getRemoteData(_url) //统一获取远程的数据
		{
			$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
				type: "get",
				url: _url,
				dataType: "json", //服务器返回的数据类型
				success: function(result) {
					if(result != null) {
						isVerify = result.ISVERIFY;
						_dataPage = result;
						getFormData(result);
						verifyStatus(result.ISVERIFY, true);
						updateData = deepCopy(result);
						currPage = result.ID; //表示传回的ID
						currid = result.ID;
						var _data = result.rows; //将获取到的数据中字头为rows的数据赋值给_data
						var amount = getAmount(_data);
						$("#input_PURCHASE_AMOUNT").textbox('setValue', amount);
						$('#tt').edatagrid('loadData', _data); //调用easyui的loadData方法，将数据写入id为tt的datagrid中
						updateLog = "";
					}

				}, //请求成功后，接受服务器传来的Json字符串，并做相应的处理
				error: function(xhr, status, error) {
					$.messager.alert("错误", "请求失败!");
				}
			});
		}

		function getAmount(_data) {
			var amount = 0;
			var _num = 0;
			for(var i = 0, len = _data.length; i < len; i++) {
				_num = parseFloat(_data[i].EVALUATE_AMOUNT)
				amount += _num;
			}
			return amount;
		}

		function GetDetailTable() { //构造datagrid中的数据
			$('#tt').edatagrid({
				height: 400,
				view: detailview,
				toolbar: _detailToolbarData, //toolbar选择自定义的名为toolbar的工具栏
				collapsible: 'true', //是否折叠：是
				singleSelect: 'true', //是否单选：是
				rownumbers: 'true',
				fitColumns: 'true', //自动调整列：是
				showFooter: 'true',
				autoSave: 'ture',
				columns: [
					[{
						field: 'INTERNALTRADE_ID',
						title: '内部商品ID',
						width: '10%',
						align: 'center',
					}, {
						field: 'INTERNAL_NAME',
						title: '*内部商品名',
						width: '15%',
						align: 'center',
					}, {
						field: 'INTERNAL_TYPE',
						title: '*内部商品类型',
						width: '15%',
						align: 'center',
					}, {
						field: 'UNIT_NAME',
						title: '*单位',
						width: '15%',
						align: 'center',
					}, {
						field: 'AMOUNT',
						title: '*应采购数量',
						width: '13%',
						align: 'center',
					}, {
						field: 'STOCKS',
						title: '*库存量',
						width: '13%',
						align: 'center',
					}, {
						field: 'EVALUATE_AMOUNT',
						title: '*预估采购数量',
						width: '13%',
						align: 'center',
						editor: {
							type: 'numberbox',
							options: {
								precision: 2,
								groupSeparator: ',',
								decimalSeparator: '.',
							}
						}
					}, ]
				],
				detailFormatter: function(index, row) {
					return '<div style="padding:2px"><table class="ddv"></table></div>';
				},
				onExpandRow: function(index, row) {
					var _url = RemoteLinkAddress + "/logistics/purchaseorder/findsales.do?PURCHASEDETAIL_ID=" + row.ID;
					var ddv = $(this).datagrid('getRowDetail', index).find('table.ddv');
					ddv.datagrid({
						url: _url,
						fitColumns: true,
						singleSelect: true,
						rownumbers: true,
						height: 'auto',
						columns: [
							[{
								field:'ORDER_NO',
								title:'订单编号',
								width: '13%',
								align: 'center',
							},{
								field: 'CUSTOMER_NAME',
								title: '用户组',
								width: '13%',
								align: 'center',
							},{
								field: 'INTERNAL_TYPE',
								title: '内部商品类型',
								width: '13%',
								align: 'center',
							},{
								field: 'INTERNAL_NAME',
								title: '内部商品名称',
								width: '13%',
								align: 'center',
							},{
								field:'UNIT_NAME',
								title:'单位',
								width:'13%',
								align: 'center',
							},{
								field: 'AMOUNT',
								title: '数量',
								width:'5%',
								align:'center'
							},{
								field:'DETAIL_STATE',
								title:'明细状态',
								width:'13%',
								align:'center'
							},{
								field: 'STATE',
								title: '单据状态',
								width:'13%',
								align:'center'
							}]
						],
						onResize: function() {
							$('#tt').datagrid('fixDetailRowHeight', index);
						},
						onLoadSuccess: function() {
							setTimeout(function() {
								$('#tt').datagrid('fixDetailRowHeight', index);
							}, 0);
						},
						onDblClickRow: function(index, row) {
						}
					});
					$('#tt').datagrid('fixDetailRowHeight', index);
				},
				onEndEdit: function(index, row, changes) { //在编辑完成或，执行该函数
					updateLog += "[预估采购量]" + updateData.rows[index].EVALUATE_AMOUNT + "[修改为]" + row.EVALUATE_AMOUNT;
					updateData.rows[index].EVALUATE_AMOUNT = row.EVALUATE_AMOUNT;
					var _rows = $("#tt").edatagrid('getRows');
					var amount = parseFloat(getAmount(updateData.rows));
					$("#input_PURCHASE_AMOUNT").textbox('setValue', amount.toFixed(2));
				},
			});
		}

		function getUpdateData() {
			updateData.PURCHASE_MAN = $("input[name='PURCHASE_MAN']").val();
			console.log(updateData);
			updateData.ORDER_NO = $("input[name='ORDER_NO']").val();
			updateData.ID = $("input[name='ID']").val();
			updateData.STOREHOUSE_ID = $("input[name='STOREHOUSE_ID']").val();
			updateData.PURCHASE_DATE = $("input[name='PURCHASE_DATE']").val();
			updateData.MEMO = $("input[name='MEMO']").val();
			updateData.LOG = updateLog;
			console.log(updateData);
			var sendData = JSON.stringify(updateData);
			submitData(sendData);
		}

		function submitData(_senddata) {
			var _url = "";
			_url = RemoteLinkAddress + "/logistics/purchaseorder/update.do";
			$.ajax({
				dataType: 'JSON',
				url: _url,
				data: 'a=' + _senddata,
				type: "POST",
				success: function(result) {
					$.messager.alert("提示", "修改保存成功");
				},
				error: function(result) {
					$.messager.alert("错误", "修改保存不成功");
				}
			});
		}

		$('#input_STOREHOUSE_NAME').combobox({
			valueField: 'ID',
			textField: 'NAME',
			panelHeight: 'auto',
			mode: 'remote',
			method: 'get',
			url: RemoteLinkAddress + "/logistics/storehouse/listall.do",
			onSelect: function(record) { //当选中数据后调用该function，并得到该combobox对应的valuefield和textfield，赋值给record
				var trade_ids = "";
				var s = updateData.rows;
				$("#input_STOREHOUSE_ID").textbox("setValue", record.ID)
				for(var i = 0; i < s.length; i++) {
					trade_ids += s[i].INTERNALTRADE_ID + ";";
				}
				getStoreHouseData(record.ID, trade_ids);
			}
		});

		function getStoreHouseData(storehouseid, trade_ids) {
			_url = RemoteLinkAddress + "/logistics/warehouse/getstock.do?STOREHOUSE_ID=" + storehouseid + "&TRADE_IDS=" + trade_ids;
			console.log(_url);
			$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
				type: "get",
				url: _url,
				dataType: "json", //服务器返回的数据类型
				success: function(result) {
					if(result != null) {
						var s = updateData.rows;
						///清空库存量
						for(var i = 0; i < s.length; i++) {
							s[i].STOCKS = 0;
						}
						for(var i = 0; i < s.length; i++) {
							for(var j = 0; j < result.length; j++) {
								if(s[i].INTERNALTRADE_ID == result[j].INTERNALTRADE_ID) {
									s[i].STOCKS = result[j].STOCK;
									s[i].EVALUATE_AMOUNT = s[i].AMOUNT - s[i].STOCKS;
									if(s[i].EVALUATE_AMOUNT <= 0) {
										s[i].EVALUATE_AMOUNT = 0;
									}
								}
							}
						}
						$('#tt').edatagrid('loadData', s);
					}
				}, //请求成功后，接受服务器传来的Json字符串，并做相应的处理
				error: function(xhr, status, error) {
					$.messager.alert("错误", "请求失败!");
				}
			});
		}

		function checkDataIntegrity() {
			var purchaseman = $("input[name='PURCHASE_MAN']").val();
			var usergroup = $("input[name='CUSTOMER_TYPE']").val();
			var purchasedate = $("input[name='PURCHASE_DATE']").val();
			var orderno = $("input[name='ORDER_NO']").val();
			var warehouse = $("input[name='STOREHOUSE_NAME']").val();
			var rowsdata = $("#tt").datagrid('getRows');
			if(purchaseman != "" && usergroup != "" && purchasedate != "" && orderno != "" && warehouse != "") {
				if(rowsdata.length != 0) {
					for(var i = 0; i < rowsdata.length; i++) {
						var internaltradeid = rowsdata[i].INTERNALTRADE_ID;
						var internalname = rowsdata[i].INTERNAL_NAME;
						var internaltype = rowsdata[i].INTERNAL_TYPE;
						var unitname = rowsdata[i].UNIT_NAME;
						var amount = rowsdata[i].AMOUNT;
						var stocks = rowsdata[i].STOCKS;
						var evaluateamount = rowsdata[i].EVALUATE_AMOUNT;
						if(internaltradeid === "" || internalname === "" || internaltype === "" || unitname === "" || evaluateamount === "" || amount === "" || stocks === "") {
							return 0;
						}
					}
				} else {
					return 0;
				}
			} else {
				return 0;
			}
		}

		function exportExcel() {
			if(currid === AddFlag) {
				$.messager.alert("警告", "该订单为新增订单，无法导出Excel！");
				return;
			}
			$.messager.confirm("提示", "确认导出Excel表格吗？", function(r) {
				if(r) {
					$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
						type: "get",
						dataType: "json", //服务器返回的数据类型
						url: RemoteLinkAddress + "/logistics/purchaseorder/excelorder.do",
						data: {
							"ID": _dataPage.ID
						},
						success: function(result) {
							window.location.href = result.path;
						}, //请求成功后，接受服务器传来的Json字符串，并做相应的处理
						error: function(xhr, status, error) {
							$.messager.alert("错误", "请求失败!");
						}
					});
				}
			});
		}
	</script>

</html>